# TODO: 导入必要的库和模块
import gradio as gr
import numpy as np
from PIL import Image
from pinecone import Pinecone, ServerlessSpec
from collections import Counter

pinecone = Pinecone(api_key="fa0e09bb-8f42-4a07-8c35-93ea8ecb5e2b")
index = pinecone.Index("mnist-index")
# TODO: 定义预测函数，这个函数将用于Gradio接口进行预测
def predict_digit(image):
    image = np.array(image['layers'][0])
    image = image[:, :, 3]
    image = Image.fromarray(image)
    image = image.resize((8,8))
    image = np.array(image)
    image = (image/ 255) * 16
    image = image.reshape(1, -1)
    query_data = image.tolist()
    results = index.query(
        vector=query_data,
        top_k=11,  # 返回距离最近的 11 个结果
        include_metadata=True  # 同时返回每个向量的元数据(包括标签)
    )
    # 从搜索结果中提取每个匹配项的标签
    labels = [match['metadata']['label'] for match in results['matches']]
    predict = Counter(labels).most_common(1)[0][0]
    return int(predict)
# TODO: 创建Gradio接口，这个接口将用于用户输入和显示预测结果
sketchpad = gr.Sketchpad(height=800, width=800)
gr.Interface(fn=predict_digit, inputs=sketchpad, outputs=gr.Label()).launch(share=True)
# TODO: 启动Gradio接口，用户可以通过这个接口进行交互
 